package com.siblings.loan.analysis.util

import android.app.Application
import androidx.fragment.app.FragmentActivity
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory

/**
 * 评分模块
 *
 * 1、首先需要集成:
 * implementation("com.google.android.play:review-ktx:2.0.1")
 *
 */
object AppReviewUtil {

    /**
     * ReviewManager 对象
     */
    private var _reviewManager: ReviewManager? = null

    /**
     * ReviewInfo 对象
     */
    private var _reviewInfo: ReviewInfo? = null

    /**
     * 初始化评分模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        _reviewManager = ReviewManagerFactory.create(context)
        val request = _reviewManager?.requestReviewFlow()
        request?.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                // 缓存起来，一般2小时内有效，能满足业务需要
                _reviewInfo = task.result
            } else {
                println("reviewErrorCode: ERROR")
            }
        }
    }

    /**
     * 调起评分流程
     *
     * @param activity Activity
     * @param completed 结束回调，收到回调后，继续走app流程
     */
    fun launchReviewFlow(activity: FragmentActivity, completed: (Boolean) -> Unit) {
        if (_reviewInfo == null) {
            completed.invoke(false)
        }

        _reviewInfo?.let {
            //调起评分
            val flow = _reviewManager?.launchReviewFlow(activity, it)

            //如果为空，直接返回
            if (flow == null) {
                completed.invoke(false)
            }

            flow?.addOnCompleteListener {
                completed.invoke(true)
            }
        }
    }
}